import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import _ from 'lodash';
import FloatLayout from '../../components/float-layout'

import { Table, Icon, Tag, message, Modal, Popover, Button } from 'antd';
import {fetchUserImages, changePage,  mPacs, removeImage, deleteImage,fetchStudyRelatedData,API_URL} from '../../store/actions';

import SearchInput from '../../components/search-input'

class _Images extends React.Component{
    constructor(props){
        super(props);
        this.state ={
            images: this.props.items || [],
            isFetch:this.props.isFetch,
            user:this.props.user,
            modalDel:{
                title:'',
                text:'',
                visible:false
            },
            studyDetail:null,
            showDetail:false
        };
        this.viewImage = this.viewImage.bind(this);
        this.delImage = this.delImage.bind(this);
        this.handleOkDel = this.handleOkDel.bind(this);
        this.handleCancelDel = this.handleCancelDel.bind(this);
        this.fetchImages = this.fetchImages.bind(this);
    }
    searchHandler(v){
        message.warning('查询功能暂不开放',1)
    }
    fetchImages(){
        const _this= this,
            uid = _this.props.user.user.user_id,
            opts = {
                userid:uid
            };
        _this.props.dispatch(fetchUserImages(opts,function(res){
            _this.setState({
                images:res.content.list
            })
        }));
    }
    componentWillMount(){
        this.fetchImages()
    }
   componentWillReceiveProps(nextProp){
       console.log('componentWillReceiveProps',nextProp.items);
        this.setState({
            images: nextProp.items,
            isFetch:nextProp.isFetch,
            imagesLen:nextProp.items && nextProp.items.length,
            user:nextProp.user
        })
    }
    viewImage(e){
        e.preventDefault();
        const study_instance_uid = e.target.id;
        if(study_instance_uid != 'null'){
            this.props.dispatch(mPacs(study_instance_uid,function(url){
                window.open(
                    url,
                    'viewer',
                    'location=no,toolbar=no,alwaysRaised=yes,screenX=0,screenY=0'
                );
            }))
        }else{
            message.warning('影像还没有准备好')
        }
    }
    delImage(e){
        e.preventDefault();
        const name = e.target.dataset.name || this.state.studyDetail.patient.name,
            studyId=e.target.dataset.id || this.state.studyDetail.study.id,
            sname = e.target.dataset.sname || this.state.studyDetail.study.check_item_name;
         this.setState({
            modalDel:{
                visible:true,
                text:`您确认要删除 ${name} 的 ${sname} 影像吗 ？`,
                title:'删除影像',
                id:studyId
            }
        });
    }
    handleOkDel(){
        const _this = this,
            studyId = _this.state.modalDel.id;
        _this.setState({
            modalDel: {
                confirmLoading: true,
                visible:true,
                text:'您确认要删除这个影像吗？',
                title:'删除影像'
            }
        },function(){
            _this.props.dispatch(removeImage(studyId,function(){
                _this.props.dispatch(deleteImage(studyId));
                message.success('删除影像成功',1,function(){
                    _this.setState({
                        modalDel: {
                            confirmLoading: false,
                            visible:false,
                            text:'',
                            title:'',
                            id:''
                        },
                        showDetail:false
                    })
                });
            }))
        });
    }
    handleCancelDel(){
        this.setState({
            modalDel:{
                visible:false
            }
        })
    }
    static contextTypes = {
        router: React.PropTypes.object
    };
    showDetail(e){
        e.preventDefault();
        const _this = this,
          study_id = e.target.dataset.study,
          studies = this.state.images,
          study = _.filter(studies,o=>{
              return o.id == study_id
          })[0];
        _this.props.dispatch(fetchStudyRelatedData(study,function(data){
            _this.setState({
                studyDetail:data,
                showDetail:true
            })
        }))
    }
    shutDetail(){
        this.setState({
            studyDetail:null,
            showDetail:false
        })
    }
    closedDetail(){
        this.setState({
            showDetail:false
        })
    }
    viewPacs(e){
        e.preventDefault();
        window.open(
          this.state.studyDetail.mp,
          'viewer',
          'location=no,toolbar=no,alwaysRaised=yes,screenX=0,screenY=0'
        );
    }
    render(){
        const _this = this,
        columns = [{
            title: '亲友姓名',
            dataIndex: 'name'
        }, {
            title: '性别',
            dataIndex: 'gender',
            render(text) {
                return text ==='M'?'男':(text === 'F'?'女':'未知')
            }
        }, {
            title: '设备类型',
            dataIndex: 'modality',
            render(text) {
                if(!!text){
                    return text
                }else{
                    return '未知设备'
                }
            }
        },{
            title: '检查项目',
            dataIndex: 'check_item_name'
        }, {
            title: '检查日期',
            dataIndex: 'studydate'
        },  {
            title: '状态',
            dataIndex: 'status',
            render(text,record){
                switch (text){
                    case -1:
                        return (<Popover content={record.memo} title="出错原因" trigger="hover">
                            <span style={{color:'red'}}>处理出错</span>
                        </Popover>);
                    case 0:
                        return <span style={{color:'#999'}}>处理中</span>;
                    case 1:
                        return <span style={{color:'#ff6600'}}>待审核</span>;
                    case 2:
                        return <span style={{color:'green'}}>审核通过</span>;
                    case 3:
                        return <span style={{color:'999'}}>已删除</span>;
                    case -2:
                        return (<Popover content={record.memo} title="驳回理由" trigger="hover">
                            <span style={{color:'#999'}}>驳回</span>
                        </Popover>);
                    default:
                        return <span style={{color:'#ccc'}}>未知状态</span>
                }
            }
        }, {
            title: '操作',
            render(record){
                const _s = record.status;
                switch (_s){
                    case -2:
                        return (
                            <div>
                                <a href="#" onClick={_this.showDetail.bind(_this)} data-study={record.id}>详情</a>
                                <span className="ant-divider"> </span>
                                <a href="#" onClick={_this.viewImage} id={`${record.study_instance_uid}`}>阅片</a>
                                <span className="ant-divider"> </span>
                                <a href="#" onClick={_this.delImage} data-sname={record.check_item_name} data-id={record.id} data-name={record.name}>删除</a>
                            </div>
                        );
                    case -1:
                    case 0:
                        return (
                            <div>
                                <a href="#" onClick={_this.showDetail.bind(_this)} data-study={record.id}>详情</a>
                                <span className="ant-divider"> </span>
                                <a href="#" onClick={_this.delImage} data-sname={record.check_item_name} data-id={record.id} data-name={record.name}>删除</a>
                            </div>
                        );
                    case 1:
                        return (
                          <div>
                            <a href="#" onClick={_this.showDetail.bind(_this)} data-study={record.id}>详情</a>
                            <span className="ant-divider"> </span>
                            <a href="#" onClick={_this.viewImage} id={`${record.study_instance_uid}`}>阅片</a>
                            <span className="ant-divider"> </span>
                            <a href="#" onClick={_this.delImage} data-sname={record.check_item_name} data-id={record.id} data-name={record.name}>删除</a>
                        </div>);
                    case 2:
                        return (
                            <div>
                                <a href="#" onClick={_this.showDetail.bind(_this)} data-study={record.id}>详情</a>
                                {/*<span className="ant-divider"> </span>
                                分享(暂不开放)*/}
                                <span className="ant-divider"> </span>
                                <a onClick={_this.viewImage} id={`${record.study_instance_uid}`}>阅片</a>
                                <span className="ant-divider"> </span>
                                <a href="#" onClick={_this.delImage} data-sname={record.check_item_name} data-id={record.id} data-name={record.name}>删除</a>
                            </div>
                        );
                    case 3:
                        return '--'
                }
            }


        }];

        const pagination = {
            total: this.state.images.length,
            showSizeChanger: true
            /*,onShowSizeChange(current, pageSize) {
                console.log('Current: ', current, '; PageSize: ', pageSize);
            },
            onChange(current) {
                console.log('Current: ', current);
            }*/
        };
        let _sd = '没有相关影像',
          extra = '',
          studyDetail = this.state.studyDetail;
        if(studyDetail){
            const patient = studyDetail.patient,
              study = studyDetail.study,
              status = study.status,
              token = this.props.user.accessToken;
            switch(status){
                case -1:
                case 0:
                    extra = (
                      <div>
                          <Button
                            data-name={patient.name}
                            data-id={study.id}
                            onClick={this.delImage.bind(this)}
                          >
                              删除
                          </Button>
                      </div>
                    );
                break;
                case 1:
                case -2:
                case 2:
                    extra = (
                      <div>
                          <Button
                            onClick={this.viewPacs.bind(this)}
                            type='primary'
                          >
                              查看影像
                          </Button>
                          &nbsp;
                          <Button
                            onClick={this.delImage.bind(this)}
                          >
                              删除
                          </Button>
                      </div>
                    );
                break;
            }
            let attachments = studyDetail.attachments.length>0?_.map(studyDetail.attachments,o=>{
                return (
                  <img
                    style={{width:'100px'}}
                    key={`${o.id}`}
                    title={`${o.name}`}
                    src={`${API_URL}attachment/${o.id}?accessToken=${token}`}
                  />)
            }):'无附件';
            _sd = (
              <div className="detailList">
                  <h2>检查信息</h2>
                  <ul className="label-list">
                      <li><label>设备类型</label>{study.modality || '--'}</li>
                      <li><label>检查部位</label>{study.bodypart || '--'}</li>
                      <li><label>检查项目</label>{study.check_item_name}</li>
                      <li><label>检查日期</label>{study.studydate || '--'}</li>
                      <li><label>检查时年龄</label>{study.patientage || '--'}</li>
                      <li><label>影像号</label>{study.study_instance_uid || '--'}</li>
                      <li><label>检查号</label>{study.accession_number || '--'}</li>
                      <li><label>检查机构</label>{study.institution || '--'}</li>
                      <li><label>症状描述</label>{study.symptom || '--'}</li>
                      <li><label>临床诊断</label>{study.diagnosis || '--'}</li>
                      <li><label>其他单据</label>{attachments}</li>
                  </ul>
                  <h2>基本信息</h2>
                  <ul className="label-list">
                      <li><label>患者姓名</label>{patient.name || '--'}</li>
                      <li><label>患者性别</label>{patient.gender == 'F'?'女':(patient.gender == 'M'?'男':'--')}</li>
                      <li><label>患者年龄</label>{patient.age || '--'}</li>
                      <li><label>患者生日</label>{patient.birthday || '--'}</li>
                      <li><label>过往病史</label>{patient.medical_history || '--'}</li>
                      <li><label>联系方式</label>{patient.mobile || '--'}</li>
                  </ul>
              </div>
            )
        }
        return(
            <div id="images">
                <div style={{overflow: 'hidden', marginBottom: '10px', padding: '10px 0'}}>
                    <div style={{float:'right'}}>
                        <SearchInput style={{ width: 200 }} onSearch={this.searchHandler.bind(this)} placeholder='请输入关键字查询' />
                    </div>
                </div>
                <Table columns={columns} dataSource={this.state.images} pagination={pagination} />
                <Modal
                    title={this.state.modalDel.title}
                    visible={this.state.modalDel.visible}
                    onOk={this.handleOkDel}
                    confirmLoading={this.state.modalDel.confirmLoading}
                    onCancel={this.handleCancelDel}
                >
                    <p>{this.state.modalDel.text}</p>
                </Modal>

                <FloatLayout
                  show={this.state.showDetail}
                  top={61}
                  left={240}
                  title='影像详情'
                  closed={this.closedDetail.bind(this)}
                  extra={extra}
                >
                    {_sd}
                </FloatLayout>
            </div>
        )
    }
}
let Images ;

export default Images = connect((state) => {
    const {isFetch,items} = state.rootReducer.images;
    const {user} = state.rootReducer;
    return {user,isFetch,items}
})(_Images)